from flask import Blueprint, request, render_template
from .models import *
import random

# 蓝图
blue = Blueprint('user', __name__)


@blue.route('/')
def index():
    return 'index'


@blue.route('/adduser/')
def adduser():
    users = []
    for i in range(10, 20):
        user = UserModel()
        user.name = f'用户-{i}'
        user.age = random.randint(10, 50)
        users.append(user)
    try:
        db.session.add_all(users)
        db.session.commit()
    except Exception as e:
        print('e:', e)
        db.session.rollback()
        db.session.flush()
    return 'OK'


@blue.route('/addmovies/')
def addmovies():
    movies = []
    for i in range(10, 20):
        movie = MovieModel()
        movie.title = f'电影-{i}'
        movies.append(movie)
    try:
        db.session.add_all(movies)
        db.session.commit()
    except Exception as e:
        print('e:', e)
        db.session.rollback()
        db.session.flush()
    return 'addmovies Ok'


@blue.route('/addcoll/')
def addcoll():
    user = UserModel().query.get(1)  #
    movie = MovieModel().query.get(4)
    user.movies.append(movie)
    db.session.commit()
    return 'addcoll OK'


@blue.route('/getcoll/')
def getcoll():
    user = UserModel().query.get(1)
    print('用户1喜欢的电影', user.movies)

    movie = MovieModel().query.get(7)
    print('电影7被那些用户收场？', movie.users)
    print(list(movie.users))

    return 'getcoll OK'


@blue.route('/deluser/')
def deluser():
    # 级联删除
    user = UserModel().query.get(1)
    db.session.delete(user)
    db.session.commit()
    return 'deluser OK'
